<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>结果：<span id="postResult"></span></div>
    <input id="name" />
    <button id="postBtn">提交 post 请求</button>
    <script>
        const postResult = document.querySelector("#postResult");
        const name = document.querySelector("#name");
        const postBtn = document.querySelector("#postBtn");


        function request(method, url, data, cb) {
            // 1 new
            const xhr = new XMLHttpRequest();
            // 2 open
            // xhr.open(method, url);
            xhr.open("POST", "http://192.168.22.24:4000/test_json");
            // 3 设置请求头
            // 把 js 对象，转换成 网络可以传输的 json 格式的 字符串
            xhr.setRequestHeader("content-type", "application/json");
            // 4 发送请求
            xhr.send(JSON.stringify(data));
            postResult.innerHTML = "请求中...";
            // 5 监听
            xhr.responseType = "json";
            xhr.addEventListener("readystatechange", () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        cb(xhr.response);
                        //   try {
                        //     const { result } = JSON.parse(xhr.responseText);
                        //   } catch (err) {
                        //     // todo:
                        //     postResult.innerHTML = "JSON 解析失败";
                        //   }
                    } else {
                        postResult.innerHTML = "请求失败";
                    }
                }
            });
        }
        postBtn.addEventListener('click', () => {
            request('POST', 'http://192.168.22.24:4000/test_json', { name: name.value }, (res) => { postResult.innerHTML = res.response })
        })
    </script>
</body>

</html>